package com.ejd.web.vo.customer;

import java.util.ArrayList;



import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.component.UIData;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;
import javax.faces.model.SelectItem;
import javax.faces.validator.ValidatorException;

import org.apache.commons.beanutils.PropertyUtils;
import org.richfaces.component.UIDataTable;



import net.sf.cglib.beans.BeanCopier;


import com.ejd.controller.LoginController;
import com.ejd.service.IConsigneeService;
import com.ejd.utils.MessageFactory;
import com.ejd.utils.RegionUtil;
import com.ejd.utils.SpringFacesUtil;
import com.ejd.utils.UIComponentUtil;
import com.ejd.utils.ValidatorUtil;

import com.ejd.web.bo.impl.Consignee;
import com.ejd.web.constant.EjdConstants;
import com.ejd.web.constant.ManageBeanConstants;
import com.ejd.web.constant.SpringBeanConstants;
import com.ejd.web.vo.common.ConsigneeVo;
import com.ejd.web.vo.common.datapage.DataPage;
import com.ejd.web.vo.genl.AbstractTableDataModel;
import com.ejd.web.vo.genl.ITableDataModel;

@ManagedBean(name="editConsigneePage")
@SessionScoped
public class EditConsigneePageBean extends AbstractTableDataModel<ConsigneeVo,ConsigneeVo> implements ITableDataModel<ConsigneeVo>,java.io.Serializable {
	
	private static final long serialVersionUID = -8106629465344224729L;
	private String action;
	
	public List<String> errorMessages = new ArrayList<String>();

	private SelectItem[] provinceItems = null;
	
	private SelectItem[] cityItems = null;
	
	private SelectItem[] countyItems = null;

	public List<String> getErrorMessages() {
		return errorMessages;
	}

	public void setErrorMessages(List<String> errorMessages) {
		this.errorMessages = errorMessages;
	}

	public SelectItem[] getProvinceItems() {
		return provinceItems;
	}

	public void setProvinceItems(SelectItem[] provinceItems) {
		this.provinceItems = provinceItems;
	}

	public SelectItem[] getCityItems() {
		return cityItems;
	}

	public void setCityItems(SelectItem[] cityItems) {
		this.cityItems = cityItems;
	}

	public SelectItem[] getCountyItems() {
		return countyItems;
	}

	public void setCountyItems(SelectItem[] countyItems) {
		this.countyItems = countyItems;
	}

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}

	
	public Object getIdItem(ConsigneeVo item) {
		return item.getId();
	}
	
	public EditConsigneePageBean() {
		super();
		this.setNumberOnePage(EjdConstants.MAX_CONSIGNEES_OF_USER);
	}

	public EditConsigneePageBean (String newAnother) {
		super();
		ConsigneeVo consigneeVo = new ConsigneeVo();
		consigneeVo.setSelected(false);
		this.setEditData(consigneeVo);
	}
	public void createNewConsignee () {
		ConsigneeVo newConsignee = new ConsigneeVo();
		newConsignee.setInvoiceTitle("");
		newConsignee.setConsigneeName("");
		newConsignee.setConsigneeMobile("");
		newConsignee.setConsigneePhone("");
		newConsignee.setConsigneeFax("");
		newConsignee.setConsigneeZip("");
		newConsignee.setConsigneeProvince("");
		newConsignee.setConsigneeCity("");
		newConsignee.setConsigneeCounty("");
		newConsignee.setConsigneeAddress("");
		newConsignee.setSelected(false);
		this.setEditData(newConsignee);
	}
	
	public String reSetConsignee() {
		operationAfterExeAction();
		EditConsigneePageBean editConsignedPage = (EditConsigneePageBean)SpringFacesUtil.getManagedBean(ManageBeanConstants.EDIT_CONSIGNEE_PAGE_BEAN_NAME);
		if (EjdConstants.ACTION_NEW_TYPE.equals(editConsignedPage.getAction())) {
			editConsignedPage.getEditData().setId(null);
			editConsignedPage.getEditData().setCustomerId("");
			editConsignedPage.getEditData().setShortName("");
			editConsignedPage.getEditData().setInvoiceTitle("");
			editConsignedPage.getEditData().setConsigneeName("");
			editConsignedPage.getEditData().setConsigneeMobile("");
			editConsignedPage.getEditData().setConsigneePhone("");
			editConsignedPage.getEditData().setConsigneeFax("");
			editConsignedPage.getEditData().setConsigneeZip("");
			editConsignedPage.getEditData().setConsigneeProvince("");
			editConsignedPage.getEditData().setConsigneeCity("");
			editConsignedPage.getEditData().setConsigneeCounty("");
			editConsignedPage.getEditData().setConsigneeAddress("");
			editConsignedPage.getEditData().setRemark("");
			editConsignedPage.getEditData().setSelected(Boolean.FALSE);
		} else if (EjdConstants.ACTION_EDIT_TYPE.equals(editConsignedPage.getAction())) {
			editConsignedPage.getEditData().setShortName(editConsignedPage.getSelectedData().getShortName());
			editConsignedPage.getEditData().setInvoiceTitle(editConsignedPage.getSelectedData().getInvoiceTitle());
			editConsignedPage.getEditData().setConsigneeName(editConsignedPage.getSelectedData().getConsigneeName());
			editConsignedPage.getEditData().setConsigneeMobile(editConsignedPage.getSelectedData().getConsigneeMobile());
			editConsignedPage.getEditData().setConsigneePhone(editConsignedPage.getSelectedData().getConsigneePhone());
			editConsignedPage.getEditData().setConsigneeFax(editConsignedPage.getSelectedData().getConsigneeFax());
			editConsignedPage.getEditData().setConsigneeZip(editConsignedPage.getSelectedData().getConsigneeZip());
			editConsignedPage.getEditData().setConsigneeProvince(editConsignedPage.getSelectedData().getConsigneeProvince());
			editConsignedPage.getEditData().setConsigneeCity(editConsignedPage.getSelectedData().getConsigneeCity());
			editConsignedPage.getEditData().setConsigneeCounty(editConsignedPage.getSelectedData().getConsigneeCounty());
			editConsignedPage.getEditData().setConsigneeAddress(editConsignedPage.getSelectedData().getConsigneeAddress());
			editConsignedPage.getEditData().setRemark(editConsignedPage.getSelectedData().getRemark());
			editConsignedPage.getEditData().setSelected(editConsignedPage.getSelectedData().isSelected());
		}
		editConsignedPage.getErrorMessages().add("");
		return null;
	}
	
	public String commitConsignee() {
		operationAfterExeAction();
		String result = null;
		if (!(LoginController.loggedIn())) {
			return EjdConstants.GO_TO_LOGIN;
		}
		validateInputDataNotEmpty(this.getEditData(),this.getErrorMessages());
		if (null != this.getErrorMessages() && this.getErrorMessages().size() > 1) {
			for (int i =0 ; i < this.getErrorMessages().size(); i ++) {
				if (this.getErrorMessages().get(i).trim().length()> 1) {
					return null;
				}
			}
		}
		LoginCustomerPageBean loginCustomerPage = (LoginCustomerPageBean)SpringFacesUtil.getManagedBean(ManageBeanConstants.LOGIN_CUSTOMER_PAGE_BEAN_NAME);
		//add consignee
		IConsigneeService<Consignee,Long> consigneeService = (IConsigneeService<Consignee,Long>) SpringFacesUtil.getSpringBean(SpringBeanConstants.CONSIGNEE_SERVICE_BEAN_NAME);
		consigneeService.setEntityClass(Consignee.class);
		consigneeService.setPKClass(Long.class);
		if (null != this.getAction() && EjdConstants.ACTION_NEW_TYPE.equals(this.getAction())) {
			List<Consignee> allConsingeesOfCustomer = consigneeService.findBy("customerId", loginCustomerPage.getCustomerInfo().getCustomerId());
			if (null != allConsingeesOfCustomer && allConsingeesOfCustomer.size() >= EjdConstants.MAX_CONSIGNEES_OF_USER) {
				this.getErrorMessages().add("对不起!您最多能添加 " + String.valueOf(EjdConstants.MAX_CONSIGNEES_OF_USER) + "项收货地址!");
				return null;
			}
			Consignee newConsignee = new Consignee();
			BeanCopier copy = BeanCopier.create(ConsigneeVo.class, Consignee.class, false);
			copy.copy(this.getEditData(),newConsignee,null);
			if (null == newConsignee.getCustomerId() || "".equals(newConsignee.getCustomerId())) {
				newConsignee.setCustomerId(loginCustomerPage.getCustomerInfo().getCustomerId());
			}
			
			consigneeService.save(newConsignee);
			EditConsigneePageBean editConsignedPage = (EditConsigneePageBean)SpringFacesUtil.getManagedBean(ManageBeanConstants.EDIT_CONSIGNEE_PAGE_BEAN_NAME);
			BeanCopier copyHere = BeanCopier.create(Consignee.class, ConsigneeVo.class, false);
			ConsigneeVo newConsigneeVo = new ConsigneeVo();
			copyHere.copy(newConsignee, newConsigneeVo, null);
			editConsignedPage.getDatas().add(newConsigneeVo);
			
		}
		//edit consignee
		if (null != this.getAction() && EjdConstants.ACTION_EDIT_TYPE.equals(this.getAction())) {
			BeanCopier copyHere = BeanCopier.create(ConsigneeVo.class, Consignee.class, false);
			Consignee consignee = new Consignee();
			copyHere.copy(this.getEditData(), consignee, null);
			consigneeService.saveOrUpdate(consignee);
			List<ConsigneeVo> dataLists = this.getDatas();
			for (ConsigneeVo cVo:dataLists) {
				if (this.getEditData().getId().equals(cVo.getId())) {
					BeanCopier copyHere1 = BeanCopier.create(ConsigneeVo.class, ConsigneeVo.class, false);
					copyHere1.copy(this.getEditData(), cVo, null);
					this.setSelectedData(cVo);
				}
			}
			
		}
		return null;
	}
	
	public String requireUpdateConsignee() {
		operationAfterExeAction();
		Map<String,UIComponent> componentMap = new HashMap<String,UIComponent>();
		List<UIComponent> te= new ArrayList<UIComponent>();
		UIViewRoot currentViewRoot = FacesContext.getCurrentInstance().getViewRoot();
		for(UIComponent component : currentViewRoot.getChildren()){ 
            te= UIComponentUtil.getComponentChildren(component,componentMap); 
        }
		UIDataTable tempTable = (UIDataTable) componentMap.get("table");
		setSelectedData((ConsigneeVo) tempTable.getRowData());
		try {
			PropertyUtils.copyProperties(this.getEditData(),this.getSelectedData());
			this.setAction(EjdConstants.ACTION_EDIT_TYPE);
		} catch(Exception e)
		{
			System.out.println(e.toString());
		}
		this.setCityItems(RegionUtil.getCityItems(this.getEditData().getConsigneeProvince()));
		this.setCountyItems(RegionUtil.getCountyItems(this.getEditData().getConsigneeCity()));
		return null;
	}
	public String selfTakeSelection() {
		operationAfterExeAction();
		//takeSelection();
		this.setAction("");
		return null;
	}
	public String deleteConsignee() {
		operationAfterExeAction();
		if (this.getEditData() == null) {
			this.getErrorMessages().add("您未选择要删除的数据!");
			return null;
		} else if (this.getEditData().getId() == null || "".equals(this.getEditData().getId())) {
			this.getErrorMessages().add("您未选择要删除的数据!");
			return null;
		}
		IConsigneeService<Consignee,Long> consigneeService = (IConsigneeService<Consignee,Long>) SpringFacesUtil.getSpringBean(SpringBeanConstants.CONSIGNEE_SERVICE_BEAN_NAME);
		consigneeService.setEntityClass(Consignee.class);
		consigneeService.setPKClass(Long.class);
		Consignee curConsignee =(Consignee) consigneeService.get(this.getEditData().getId());
		
		if (null == curConsignee) {
			this.getErrorMessages().add("未找到匹配的数据供删除!");
			return null;
		} else {
			consigneeService.delete(this.getEditData().getId());
			this.getErrorMessages().add("您选择的联系人:" + this.getSelectedData().getShortName() + " 已成功删除!");
			this.getDatas().remove(this.getSelectedData());
			ConsigneeVo newConsigneeVo = new ConsigneeVo();
			newConsigneeVo.setSelected(false);
			this.setEditData(newConsigneeVo);
			this.setAction(EjdConstants.ACTION_NEW_TYPE);
		}
		return null;
	}
	public String deleteConsigneeByEachItem() {
		operationAfterExeAction();
		Map<String,UIComponent> componentMap = new HashMap<String,UIComponent>();
		List<UIComponent> te= new ArrayList<UIComponent>();
		UIViewRoot currentViewRoot = FacesContext.getCurrentInstance().getViewRoot();
		for(UIComponent component : currentViewRoot.getChildren()){ 
            te= UIComponentUtil.getComponentChildren(component,componentMap); 
        }
		UIDataTable tempTable = (UIDataTable) componentMap.get("table");
		ConsigneeVo delConsigneeVo = (ConsigneeVo) tempTable.getRowData();
		IConsigneeService<Consignee,Long> consigneeService = (IConsigneeService<Consignee,Long>) SpringFacesUtil.getSpringBean(SpringBeanConstants.CONSIGNEE_SERVICE_BEAN_NAME);
		consigneeService.setEntityClass(Consignee.class);
		consigneeService.setPKClass(Long.class);
		Consignee curConsignee =(Consignee) consigneeService.get(delConsigneeVo.getId());
		if (null == curConsignee) {
			this.getErrorMessages().add("未找到匹配的数据供删除!");
			return null;
		} else {
			consigneeService.delete(delConsigneeVo.getId());
			this.getDatas().remove(delConsigneeVo);
			//clear EditData and selectedData if delete data same as.
			if (null != this.getEditData() && (this.getEditData().getId() == (delConsigneeVo.getId()))) {
				ConsigneeVo newConsigneeVo = new ConsigneeVo();
				newConsigneeVo.setSelected(false);
				this.setEditData(newConsigneeVo);
				this.setSelectedData(newConsigneeVo);
				this.setAction(EjdConstants.ACTION_NEW_TYPE);
				this.getErrorMessages().clear();
			}
		}
		return "myAddress?faces-redirect=true";
	}
	
	public String preDddConsignee(){
		operationAfterExeAction();
		this.setAction(EjdConstants.ACTION_NEW_TYPE);
		ConsigneeVo newConsigneeVo = new ConsigneeVo();
		newConsigneeVo.setSelected(false);
		this.setEditData(newConsigneeVo);
		this.setSelectedData(newConsigneeVo);
		this.setCityItems(RegionUtil.getCityItems(this.getEditData().getConsigneeProvince()));
		this.setCountyItems(RegionUtil.getCountyItems(this.getEditData().getConsigneeCity()));
		return null;
	}
	private void operationAfterExeAction(){
		this.getErrorMessages().clear();
		this.getErrorMessages().add("");
	}
	// getTotalCount() in this bean not used , so it's not need to realize
	public int getTotalCount() {
		return 0;
	}
	// getDataPage() in this bean not used , so it's not need to realize
	public DataPage<ConsigneeVo> getDataPage(int startRow, int pageSize) {
		return null;
	}
	// getDataPage() in this bean not used , so it's not need to realize
	public DataModel getDataModel(){
		return null;
	}
	//in this bean data must from DB first.
	public DataModel getCurrDataModel() {
		 /*DataModel cdataModel = null;
		 cdataModel= new ExtendedTableDataModel<ConsigneeVo>(new DataProvider<ConsigneeVo>(){

			private static final long serialVersionUID = 5054087821033164847L;

			public ConsigneeVo getItemByKey(Object key) {
				for(ConsigneeVo c : getDatas()){
					if (key.equals(getKey(c))){
						return c;
					}
				}
				return null;
			}

			public List<ConsigneeVo> getItemsByRange(int firstRow, int endRow) {
				return (null != getDatas())?getDatas().subList(firstRow, endRow):null;
			}

			public Object getKey(ConsigneeVo item) {
				return getIdItem(item);
			}

			public int getRowCount() {
				return (null != getDatas())?getDatas().size():0;
			}
			
		});*/
	
	return null;
		
	}
	private static List<String> validateInputDataNotEmpty(ConsigneeVo consigneeVo,List<String> errorMessages){
		List<String> result = errorMessages;
		FacesMessage message;
		if (ValidatorUtil.isEmpty(null == consigneeVo.getShortName()?null:consigneeVo.getShortName())) {
			
			message = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME, "address.short.must.input.error.message", FacesMessage.SEVERITY_ERROR);
	 		errorMessages.add(message.getDetail());
		}
		if (ValidatorUtil.isEmpty(null == consigneeVo.getConsigneeName()?null:consigneeVo.getConsigneeName())) {
			
			message = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME, "consignee.name.must.input.error.message", FacesMessage.SEVERITY_ERROR);
	 		errorMessages.add(message.getDetail());
		}
		if (ValidatorUtil.isEmpty(null == consigneeVo.getConsigneeMobile()?null:consigneeVo.getConsigneeMobile()) && ValidatorUtil.isEmpty(null == consigneeVo.getConsigneePhone()?null:consigneeVo.getConsigneePhone())) {
			
			message = MessageFactory.getMessage(EjdConstants.USER_BUNDLE_NAME, "consignee.movileorphone.must.input.error.message", FacesMessage.SEVERITY_ERROR);
	 		errorMessages.add(message.getDetail());
		}
		return result;
	}
	public void changeProvince(ValueChangeEvent evt) {
		String newProvince = (String) evt.getNewValue();
		this.getEditData().setConsigneeCity(EjdConstants.BLANK_VALUE_SELECT_ITEM);
		this.setCityItems(RegionUtil.getCityItems(newProvince));
		this.getEditData().setConsigneeCounty(EjdConstants.BLANK_VALUE_SELECT_ITEM);
		this.setCountyItems(RegionUtil.getCountyItems(EjdConstants.BLANK_VALUE_SELECT_ITEM));
		
	}
	public void changeCity(ValueChangeEvent evt) {
		String newCity = (String) evt.getNewValue();
		this.getEditData().setConsigneeCounty(EjdConstants.BLANK_VALUE_SELECT_ITEM);
		this.setCountyItems(RegionUtil.getCountyItems(newCity));
	}
}
